<template>
  <div class="search-container">
    <form action="/">
      <van-search
        v-model="searchText"
        placeholder="请输入搜索关键词"
        shape="round"
        input-align="center"
        show-action
        background="#3196fa"
        @search="onSearch(searchText)"
        @cancel="$router.back()"
        @focus="isResultShow=false"
      />
      <!-- :search-text 传递要请求的值给子组件去请求数据 子组件props接受-->
    </form>
    <!-- 搜索结果 -->
    <search-result
      v-if="isResultShow"
      :search-text="searchText"
    >
      >
    </search-result>
    <!-- 搜索建议,联想 -->
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    >
    </search-suggestion>
    <!-- 搜索历史记录 -->
    <search-history
      v-else
      :search-history="searchHistory"
      @search="onSearch"
      @update-history="searchHistory = $event"
    >
    </search-history>
  </div>
</template>
<script>
import searchSuggestion from "./components/search-suggestion.vue"
import searchHistory from "./components/search-history.vue"
import searchResult from "./components/search-result.vue"
import { getItem, setItem } from "@/utils/storage"
import { getSearchHistory } from "@/api/search"
export default {
  data: () => ({
    searchText: '',
    isResultShow: false,
    searchHistory: getItem('search-history') || []
  }),
  methods: {
    onSearch(searchText) {
      this.searchText = searchText
      const index = this.searchHistory.indexOf(searchText)
      if (index !== -1) {
        this.searchHistory.splice(index, 1)
      }
      this.searchHistory.unshift(searchText)
      console.log(this.searchHistory)
      this.isResultShow = true
    },
    async getSearchHistory() {
      const { data } = await getSearchHistory()
      console.log(data)
    }
  },
  components: {
    searchSuggestion,
    searchHistory,
    searchResult
  },
  created() {
    this.getSearchHistory()
  },
  watch: {
    searchHistory() {
      setItem('search-history', this.searchHistory)
    }
  }
}
</script>
<style lang="less">
.search-container {
  .search-result {
    position: fixed;
    top: 54px;
    left: 0;
    bottom: 0;
    overflow-y: auto;
    right: 0;
  }
}
</style>
